<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert title="添加商品" center type="info" show-icon></el-alert>
      <!-- 分步组件 -->
      <el-steps :active="active" finish-status="success">
        <el-step description='基本信息'></el-step>
        <el-step description='商品参数'></el-step>
        <el-step description='商品属性'></el-step>
        <el-step description='商品图片'></el-step>
        <el-step description='商品内容'></el-step>
        <el-step description='完成'></el-step>
      </el-steps>
      <el-form ref='addFormRef' :model='productInfo' label-width='90px' :rules='productRules'>
        <el-tabs v-model='activeTab' tab-position="left" @tab-click='handleClick'>
        <el-tab-pane label="基本信息" name='0'>
          <el-form-item label='商品名称' prop='goods_name'>
            <el-input placeholder='请输入商品名称' v-model='productInfo.goods_name'></el-input>
          </el-form-item>
          <el-form-item label='商品价格' prop='goods_price'>
            <el-input type='number' :min='1' v-model="productInfo.goods_price"></el-input>
          </el-form-item>
          <el-form-item label='商品重量' prop='goods_weight'>
            <el-input type='number' :min='1' v-model="productInfo.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label='商品数量' prop='goods_number'>
            <el-input type='number' :min='1' v-model="productInfo.goods_number"></el-input>
          </el-form-item>
          <el-form-item label='商品分类'>
            <el-cascader v-model="productInfo.goods_cat" :options="options" @change="handleChangeCat" :props='props'></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label='商品参数' name='1'>
          <el-form-item :label='item.attr_name' v-for='item in manyTabledata' :key='item.attr_id'>
            <!-- 复选框组 -->
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label='商品属性' name='2'>
          <!-- 要渲染的表单item项 -->
          <el-form-item :label="item.attr_name" v-for="item in onlyTabledata" label-width='150px' :key="item.attr_id">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name='3'>
        <!-- name属性是图片上传的字段名 -->
        <!-- drag是否启动拖拽上传 -->
        <!-- on-success文件上传成功的钩子函数 -->
          <el-upload
          action="http://127.0.0.1:8888/api/private/v1/upload"
          :headers='headers'
          name='file'
          list-type="picture-card"
          :on-success="handleSuccess"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name='4'>
        <!-- 富文本编辑器 -->
        <quill-editor v-model="productInfo.gooos_introduce"
            ref="productdescRef">
        </quill-editor>
        <el-button style="margin-top: 12px" type='primary' @click="addGood">添加商品</el-button>
        </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 已上传的图片列表
      imgList: [],
      active: 0,
      // 添加的商品对象
      productInfo: {
        goods_name: '',
        // 商品所属的分类列表
        goods_cat: [],
        goods_price: '0',
        goods_number: '0',
        goods_weight: '0',
        gooos_introduce: '',
        pics: [],
        // 商品参数列表
        attrs: []
      },
      // 当前活动的tab标签
      activeTab: '0',
      // 分类信息
      options: [],
      // 级联菜单展示对象props
      props: {
        label: 'cat_name',
        children: 'children',
        value: 'cat_id'
      },
      // 图片上传地址
      dialogImageUrl: '',
      // 图片预览框的显示隐藏
      dialogVisible: false,
      // 图片上传所接受的请求头信息
      headers: {
        Authorization: sessionStorage.getItem('token')
      },
      // 添加商品信息验证规则
      productRules: {
        goods_name: [
          { required: true, message: '商品名不能为空', trigger: 'blur' }
        ]
      },
      // 动态属性列表
      manyTabledata: [],
      // 静态属性列表
      onlyTabledata: []
    }
  },
  methods: {
    next () {
      this.active += 1
      this.activeTab = this.active.toString()
      console.log(this.activeTab)
    },
    // // 切换标签之前
    // beforeleaveTag (activeName, oldActiveName) {
    //   // 如果是第一个标签页切换到第二个,需要判断是否分类已经选择
    //   if (oldActiveName.index === '0' && this.productInfo.goods_cat.length !== 3) {
    //     this.$message.error('请先选择商品分类')
    //     return false
    //   }
    // },
    // 处理选项卡被切换点击事件
    async handleClick (tab, event) {
      const cateId = this.productInfo.goods_cat.length === 3 ? this.productInfo.goods_cat[2] : null
      // 动态切换,切换到不同的目录需要获取不同的数据并渲染,且切换前需要预校验
      if (this.activeTab === '1') {
        const { data: res } = await this.$http.get(`categories/${cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error('请选择商品三级分类')
        // 遍历获取的数据里的array给manytabledata
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTabledata = res.data
      } else if (this.activeTab === '2') {
        const { data: res } = await this.$http.get(`categories/${cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error('获取静态分类属性失败')
        this.onlyTabledata = res.data
        console.log(this.onlyTabledata)
      }
      this.active = +tab.index
    },
    // 获取分类信息
    async getCategories () {
      const { data: res } = await this.$http.get('categories?type=3')
      if (res.meta.status !== 200) return this.$message.error('获取分类列表信息失败')
      this.options = res.data
    },
    // 分类节点选中时
    handleChangeCat (val) {
      console.log(val)
    },
    // 图片预览函数
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 图片上传成功函
    handleSuccess (res, file, imgList) {
      this.productInfo.pics.push({
        pic: res.data.tmp_path
      })
      this.imgList = imgList
    },
    // 移除图片
    handleRemove (file) {
      const pathImg = file.response.data.tmp_path
      // 过滤掉添加商品对象里的pics数组里的pathimg
      this.productInfo.pics = this.productInfo.pics.filter(item => item.pic !== pathImg)
      // 删除预览图片列表里的
      const id = this.imgList.findIndex(item => item.uid === file.uid)
      this.imgList.splice(id, 1)
    },
    // 添加商品
    addGood () {
      // 处理选择的分类结果
      this.productInfo.goods_cat = this.productInfo.goods_cat.join()
      // 处理动态属性参数
      this.manyTabledata.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.productInfo.attrs.push(newInfo)
      })
      // 处理静态属性参数
      this.onlyTabledata.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.productInfo.attrs.push(newInfo)
      })
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('goods', this.productInfo)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  created () {
    this.getCategories()
  }
}
</script>

<style lang="less" scoped>
  .el-tabs{
    margin-top: 20px
  }
  .el-alert{
    margin-bottom: 20px;
  }
</style>
